package com.vgemv.jsutilitysdk.activity.BaseActivity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;


import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import com.vgemv.jsutilitysdk.Application.JsBaseApplication;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;

//1类权限,是需要再Manifest.xml中声明的.

public class JsBaseActivity extends Activity{
    //Permission1 权限
    static public final int PermissionRequstId_Permission1 = 1001;
    //浮窗权限
    static public final int PermissionRequstId_FloatWindow = 1002;
    //录制屏幕权限.
    static public final int PermissionRequstId_CaptureScreen = 1003;

    private TaskStep mStep;

    //传递的各种Key
    //代入需要申请的权限
    static public final String PermisionActivityKeyPermissionRequest = "PermisionActivityKeyPermissionRequest";
    //权限申请结果
    static public final String PermisionActivityKeyPermissionResponse = "PermisionActivityKeyPermissionResponse";
    static public final String PermisionActivityKeyImageResourceId = "PermisionActivityKeyImageResourceId";

    //1类权限中,没有同意的.
    private ArrayList<String> mal_missingPermissions;
    //1类权限中,被拒绝的.
    private ArrayList<String> mal_rejectedPermissions;

    private  int i = 1;

    private HandlerThread mHandlerThread = new HandlerThread("RequestAuthority");
    private AuthorityHandler mAuthorityHandler;
    static public MediaProjection smMediaProjection;


    private String[] mal_permission;
    //所有的1类权限
    private ArrayList<String> mal_permission1 = new ArrayList<String>();

    private boolean mb_isNeedFloatPermision = false;
    private boolean mb_isNeedRecordPermission = false;

    //权限处理结果的回调
    public  IPermissionRequestCallback mPermissionCallback;


    class AuthorityHandler extends Handler {
        public AuthorityHandler(Looper looper) {
            super(looper);
        }

        /**
         * Subclasses must implement this to receive messages.
         */
        public void handleMessage( Message msg) {

        }
    }


//    public  GajPermissionActivity.IAuthorityActivityCallback mPermissionCallback = new IAuthorityActivityCallback() {
//
//
//        @Override
//        public void onAuthorityAllGranted() {
//            Intent data = new Intent();
//            String msg = "All permission granted!";
//            data.putExtra(PermisionActivityKeyPermissionResponse,msg);
//            setResult(RESULT_OK,data);
//            GajPermissionActivity.this.finish();
//        }
//
//        @Override
//        public void onAuthorityDenied() {
//
//        }
//
//        @Override
//        public void onFloatAuthorityDenied() {
//
//        }
//
//        @Override
//        public void onScreenCaptureAuthorityGranted(MediaProjection mediaProjection) {
////            Intent data = new Intent();
//////            data.putExtra("MsgB",mediaProjection);
////            Bundle bundle= new Bundle();
////
////            data.putExtra("MsgB",msg);
////            setResult(1,data);
////            AuthorityActivity.this.finish();
//        }
//
//        @Override
//        public void onScreenCaptureAuthorityDenied() {
//
//        }
//    };

    //2 Inner
    //2.1 Inner Interface
    public interface IPermissionRequestCallback {
        //所有权限获取成功;
        public void onAuthorityAllGranted();
        //第一类权限获取失败
        public void onAuthorityNotAllGranted(ArrayList notGrantedPermissions);
//        //第二类权限获取失败
//        public void onFloatAuthorityDenied();
//        //第二类权限获取失败
//        public void onScreenCaptureAuthorityGranted(MediaProjection mediaProjection);
//        public void onScreenCaptureAuthorityDenied();
    }


    // 3 interface

    /**
     * 1,请求一次所有的权限,然后将结果通过回调的方式返回.
     * @param permissions
     */
    public void requestAllPermission( String [] permissions ,IPermissionRequestCallback callback) {
        mal_permission = permissions;
        mPermissionCallback = callback;
        /*
        1,将权限分好类,目前分为3类
         1类权限,浮窗,录屏
         */
        for(String permission : permissions) {
            if(permission.equals(Manifest.permission.SYSTEM_ALERT_WINDOW)) {
                mb_isNeedFloatPermision = true;
            }
            else if(permission.equals(Context.MEDIA_PROJECTION_SERVICE)) {
                mb_isNeedRecordPermission = true;
            }
            else {
                mal_permission1.add(permission);
            }
        }
        mStep = TaskStep.CheckPermission1;


//        mHandlerThread.start();
//        mAuthorityHandler = new AuthorityHandler(mHandlerThread.getLooper());
        requestStep();
    }




    enum TaskStep {
        Init,
        CheckPermission1,
        CheckPermissionFloat,
        CheckPermissionCapture,
        Done
    }


    /*
    目标1,确保所有的权限获取完毕.并调回到主页面. not elegant,depracated.
    目标2,请求一次所有的权限,然后检查获取情况,返回给callback,让callback决定如何继续.
     */
    public void requestStep() {
        switch(mStep){
            case Init: {
                return;
            }
            case CheckPermission1:{
                mStep = TaskStep.CheckPermissionFloat;
                if(!isPermission1AllMeets()){
                    requestPermission1();
                }
                else {
                    requestStep();
                }
                return;
            }
            case CheckPermissionFloat: {
                mStep = TaskStep.CheckPermissionCapture;
                if(!isFloatPermissionMeets()){
                    requestFloatPermission(this);
                }else {
                    requestStep();
                }
                return;
            }
            case CheckPermissionCapture: {
                mStep = TaskStep.Done;
                if(!isCaptureScreenPermissionMeets()) {
                    requestCaptureScreenPermission();
                }
                else {
                    requestStep();
                }
                return;
            }
            case Done: {
                checkPermissionResultAndReturn();
            }
        }
    }
    public void checkPermissionResultAndReturn() {

        ArrayList al_notGranted = new ArrayList<String>();
        for(String permission : mal_permission) {
            if(permission.equals(Manifest.permission.SYSTEM_ALERT_WINDOW)) {
                boolean b = isFloatPermissionMeets();
                if(!b) {
                    al_notGranted.add(Manifest.permission.SYSTEM_ALERT_WINDOW);
                }
            }
            else if(permission.equals(Context.MEDIA_PROJECTION_SERVICE)) {
                boolean b = isCaptureScreenPermissionMeets();
                if(!b) {
                    al_notGranted.add(Context.MEDIA_PROJECTION_SERVICE);
                }
            }
            else {
                boolean b = isPermissionGranted(permission);
                if(!b) {
                    al_notGranted.add(permission);
                }
            }
        }
        if(al_notGranted.size()> 0) {
            if(mPermissionCallback != null) {
                mPermissionCallback.onAuthorityNotAllGranted(al_notGranted);
            }
        }
        else {
            if(mPermissionCallback != null) {
                mPermissionCallback.onAuthorityAllGranted();
            }
        }
    }

    public boolean isCaptureScreenPermissionMeets() {
        if(mb_isNeedRecordPermission) {
            return false;
        }
        else {
            return true;
        }
    }


    public boolean isPermission1AllMeets() {
        //permission1数组为空,直接返回true
        if(mal_permission1 == null || mal_permission1.size() == 0) {
            return true;
        }
        else {
            //逐个检查mal_permission1数组中的权限是否满足,如果有未满足的,返回false.
                mal_missingPermissions = new ArrayList<String>();
                mal_rejectedPermissions = new ArrayList<String>();
                for (String permission : mal_permission1) {
                    if(isPermissionGranted(permission) == false) {
                        //有权限被拒绝.
                        if(couldShowRequestPermissionDialog(permission)) {
                            mal_rejectedPermissions.add(permission);
                        }
                        else {
                            mal_missingPermissions.add(permission);
                        }
                    }
                }
                if (mal_missingPermissions.size() > 0 || mal_rejectedPermissions.size()>0) {
                    return false;
                } else {
                    return true;
                }
        }

    }

    //检查1类权限是否被满足
    public boolean isPermissionGranted(String permission) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(permission)
                    == PackageManager.PERMISSION_GRANTED) {
                return true;
            } else {
                return false;
            }
        }
        else{
                return false;
            }
    }

    //检查1类权限系统弹窗是否可以被弹出
    public boolean couldShowRequestPermissionDialog(String permission) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (shouldShowRequestPermissionRationale(permission)) {
                return true;
            } else {
                return false;
            }
        }
        else{
            return false;
        }
    }




    /**
     * 申请没有获得的一类权限
     */
    public void requestPermission1() {
        if(mal_missingPermissions.size() > 0) {
            String[] check = new String[mal_missingPermissions.size()];
            mal_missingPermissions.toArray(check);
            ActivityCompat.requestPermissions(this, check, i);
        }
        else {
            if(mal_rejectedPermissions.size() > 0 ) {
                showCustomRequestPermissionDialog(mal_rejectedPermissions);
            }
        }
    }

    public void showCustomRequestPermissionDialog(ArrayList<String> permissions) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

        StringBuilder sb_permissionInfo = new StringBuilder();
        sb_permissionInfo.append("为了方便您使用程序,请前往设置页面打开以下权限:\n");
        for(String permission:permissions) {
            sb_permissionInfo.append(permission);
            sb_permissionInfo.append("\n");
        }
        alertDialogBuilder.setMessage(sb_permissionInfo.toString());

        alertDialogBuilder.setPositiveButton("确认",new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                //点击确认,跳转到安卓设置浮窗的页面.
                int sdkInt = Build.VERSION.SDK_INT;
                 if (sdkInt >= Build.VERSION_CODES.M) {

                     //android.settings.APPLICATION_SETTINGS

                }

                if (Build.VERSION.SDK_INT >= 9) {


                    Intent intent = new Intent();
//                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                    intent.setData(Uri.fromParts("package",getPackageName(), null));
                    startActivityForResult(intent, PermissionRequstId_Permission1);

                } else if (Build.VERSION.SDK_INT <= 8) {
                    //6.0-8.0
                    Intent intent = new Intent();
//                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
                    intent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
//                    intent.setData(Uri.parse("package:" + getPackageName()));
                    startActivityForResult(intent, PermissionRequstId_Permission1);
                }
                else {
                    //4.4-6.0一下
                    //无需处理了
                }
            }

        });
        alertDialogBuilder.setNegativeButton("取消",new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface var1, int var2) {
//                onFloatPermissionAccepted(false);
                if(mPermissionCallback != null) {
                    mPermissionCallback.onAuthorityNotAllGranted(null);
                }
                else {
                    requestStep();
                }
            }
        });
        alertDialogBuilder.setCancelable(false);
        //点击外面就相当于点击了取消.
//        alertDialogBuilder.setCancelable(true);

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();

    }


    /*
    权限获取后的回调.
     */
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        requestStep();
    }


    /*
    弹窗权限是否满足
     */
    public boolean isFloatPermissionMeets() {
        if(mb_isNeedFloatPermision) {
            if(hasFloatPermission()) {
                return true;
            }
            else {
                return false;
            }
        }
        else {
            return true;
        }
    }


    //检查是否有弹窗权限
    public  boolean hasFloatPermission() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            return true;
        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            try {
                Class cls = Class.forName("android.content.Context");
                Field declaredField = cls.getDeclaredField("APP_OPS_SERVICE");
                declaredField.setAccessible(true);
                Object obj = declaredField.get(cls);
                if (!(obj instanceof String)) {
                    return false;
                }
                String str2 = (String) obj;
                obj = cls.getMethod("getSystemService", String.class).invoke(JsBaseApplication.sharedInstance(), str2);
                cls = Class.forName("android.app.AppOpsManager");
                Field declaredField2 = cls.getDeclaredField("MODE_ALLOWED");
                declaredField2.setAccessible(true);
                Method checkOp = cls.getMethod("checkOp", Integer.TYPE, Integer.TYPE, String.class);
                int result = (Integer) checkOp.invoke(obj, 24, Binder.getCallingUid(), JsBaseApplication.sharedInstance().getPackageName());
                return result == declaredField2.getInt(cls);
            } catch (Exception e) {
                return false;
            }
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                //高版本的api
                AppOpsManager appOpsMgr = (AppOpsManager) JsBaseApplication.sharedInstance().getSystemService(Context.APP_OPS_SERVICE);
                if (appOpsMgr == null)
                    return false;
                int mode = appOpsMgr.checkOpNoThrow("android:system_alert_window", android.os.Process.myUid(), JsBaseApplication.sharedInstance()
                        .getPackageName());
                //这个值确实能反映设置中是否开启了权限.
                boolean lb_canDrawOverlays = Settings.canDrawOverlays(JsBaseApplication.sharedInstance());
//				AppOpsManager是啥???

//				return Settings.canDrawOverlays(context) || mode == AppOpsManager.MODE_ALLOWED || mode == AppOpsManager.MODE_IGNORED;
                return Settings.canDrawOverlays(JsBaseApplication.sharedInstance());
            } else {
                return Settings.canDrawOverlays(JsBaseApplication.sharedInstance());
            }
        }
    }

    // 3 Interface

    /**
     * 请求屏幕录制权限
     *
     */
    public void requestCaptureScreenPermission() {
        MediaProjectionManager mMediaProjectionManager = (MediaProjectionManager) getApplicationContext().getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        Intent captureIntent = mMediaProjectionManager.createScreenCaptureIntent();
        startActivityForResult(captureIntent, PermissionRequstId_CaptureScreen);
    }


    /*请求弹窗权限*/
    /*请求弹窗权限,需要从一个Activity跳转到设置页面,所以需要传入一个Activity.
     *
     *1,点击取消,则调用授权失败按钮.
     *2,点击ok,跳转到设置页面,让用户自己设置.
     */
    public  void requestFloatPermission(final Activity activity) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
        alertDialogBuilder.setMessage("请打开弹窗权限");
        alertDialogBuilder.setPositiveButton("确认",new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                //点击确认,跳转到安卓设置浮窗的页面.
                int sdkInt = Build.VERSION.SDK_INT;
                if (sdkInt >= Build.VERSION_CODES.M) {
                    //6.0-8.0
                    //android.settings.action.MANAGE_OVERLAY_PERMISSION
                    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                    intent.setData(Uri.parse("package:" + activity.getPackageName()));
                    activity.startActivityForResult(intent, PermissionRequstId_FloatWindow);
                }
                else {//4.4-6.0一下
                    //无需处理了
                }
            }

        });
        alertDialogBuilder.setNegativeButton("取消",new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface var1, int var2) {
//                onFloatPermissionAccepted(false);
                if(mPermissionCallback != null) {
                    mPermissionCallback.onAuthorityNotAllGranted(null);
                }
            }
        });
        alertDialogBuilder.setCancelable(false);
        //点击外面就相当于点击了取消.
//        alertDialogBuilder.setCancelable(true);

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }


    /** Activity执行结果，回调函数 */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String message = String.format("RequestCode:%d,resultCode:%d,Intent:",requestCode,resultCode);
//		Toast.makeText(this,message,Toast.LENGTH_LONG).show();


        if(requestCode == PermissionRequstId_Permission1) {
            //获取浮窗权限的Intent
            if(resultCode == Activity.RESULT_OK) {
                //获得了弹窗权限
            }
            else if(resultCode == Activity.RESULT_CANCELED) {
                //没有获得弹窗权限

            }
            requestStep();

        }
        if(requestCode == PermissionRequstId_FloatWindow) {
            //获取浮窗权限的Intent
            if(resultCode == Activity.RESULT_OK) {
                //获得了弹窗权限
            }
            else if(resultCode == Activity.RESULT_CANCELED) {
                //没有获得弹窗权限

            }
            requestStep();
        }
        else if(requestCode == PermissionRequstId_CaptureScreen) {
            if(resultCode == RESULT_OK) {
                MediaProjectionManager mMediaProjectionManager = (MediaProjectionManager) getApplicationContext().getSystemService(MEDIA_PROJECTION_SERVICE);
                MediaProjection mediaProjection = mMediaProjectionManager.getMediaProjection(resultCode, data);
                smMediaProjection = mediaProjection;
                //只有返回了ok,才能创建成功.
                mPermissionCallback.onAuthorityAllGranted();
            }
            else {
                requestCaptureScreenPermission();
            }
        }
    }
}
